package com.superhelper.superhelper_web.service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.superhelper.common.domain.AuserShop;
import com.superhelper.common.domain.TakeOutOrderProcess;
import com.superhelper.superhelper_web.domain.DeliverRecordOrder;
import com.superhelper.superhelper_web.domain.Order;
import com.superhelper.superhelper_web.domain.OrderGroup;
import com.superhelper.superhelper_web.domain.OrderGroupItem;
import com.superhelper.superhelper_web.domain.PageModel;
import com.superhelper.superhelper_web.mapper.DeliverMapper;
import com.superhelper.superhelper_web.mapper.OrderMapper;

@Service
public class OrderService {
	protected Logger log = LoggerFactory.getLogger(this.getClass());
	@Autowired(required = true)
	private OrderMapper orderMapper;
	@Autowired
	private ElemeService elemeService;
	@Autowired
	private DeliverMapper deliverMapper;
	@Autowired
	private DeliverService deliverService;
	@Autowired
	private MtService mtService;

	public List<Order> getTakeOutOrder(PageModel pageModel,Date date_sub) {
		int count = orderMapper.getTakeout_orderCount(pageModel,date_sub);
		pageModel.setRecordCount(count);
		List<Order> list = orderMapper.getTakeout_order(pageModel,date_sub);
		Map<Long, Order> map = new HashMap<Long, Order>();
		for (Order o : list) {
			map.put(o.getId(), o);
		}
		if (map.keySet().size() > 0) {
			List<Long> recordList = deliverMapper
					.getDeliverRecordByOrderIds(StringUtils.join(map.keySet(),
							","));
			for (Long id : recordList) {
				if (map.containsKey(id)) {
					map.get(id).setIsDeliver(true);
				} else {
					map.get(id).setIsDeliver(false);
				}
			}
		}
		this.addGroupforOrder(list);
		return list;
	}

	private void addGroupforOrder(List<Order> list) {
		List<Long> orderIds = new ArrayList<Long>();
		for (Order order : list) {
			orderIds.add(order.getId());
		}
		if (orderIds.size() > 0) {
			List<OrderGroupItem> items = orderMapper
					.getTakeOutOrderGroupItem(StringUtils.join(orderIds, ","));
			// Long seconds = System.currentTimeMillis() / 1000;
			for (Order order : list) {
				// Long activeTime = order.getActiveAt().getTime() / 1000;
				// if (seconds - activeTime > 5 * 60) {// 5分钟内接单
				// order.setDisplayTime("0");
				// } else {
				// Long disTime = seconds - activeTime;
				// long m = disTime / 60;
				// long s = disTime % 60;
				// order.setDisplayTime(m + ":" + s);
				// }
				for (OrderGroupItem item : items) {
					if (order.getItems() == null) {
						order.setItems(new ArrayList<OrderGroupItem>());
					}
					if (order.getOrderGroups() == null) {
						order.setOrderGroups(new ArrayList<OrderGroup>());
					}
					if (order.getId().equals(item.getOrderId())) {

						if (item.getType().equals("normal")) {// 统计商品份数
							order.getItems().add(item);
							order.setTotalQuantity(order.getTotalQuantity()
									+ item.getQuantity());
						} else if (item.getType().equals("extra")) {// 其他费用
							OrderGroup group = new OrderGroup();
							group.setName(item.getName());
							group.setQuantity(item.getQuantity());
							group.setPrice(item.getPrice());
							order.getOrderGroups().add(group);
						}
					}
				}
			}
		}
	}

	// public Order getOrderByPlfOrderId(String orderId, String type) {
	// Order order = orderMapper.getOrderByPlfOrderId(orderId, type);
	// if (order != null) {
	// List<Order> list = new ArrayList<Order>();
	// list.add(order);
	// this.addGroupforOrder(list);
	// }
	// return order;
	// }

	public List<Order> querOrderToPrint(List<String> shopIds, Date time) {
		if (shopIds.isEmpty()) {
			return Collections.emptyList();
		}
		orderMapper.updateStatusByTime(StringUtils.join(shopIds, ","), time);
		List<TakeOutOrderProcess> processList = orderMapper
				.querOrderToPrint(StringUtils.join(shopIds, ","));
		List<Long> orderids = new ArrayList<Long>();
		for (TakeOutOrderProcess p : processList) {
			orderids.add(p.getOrderId());
		}
		if (orderids.isEmpty()) {
			return Collections.emptyList();
		}
		List<Order> orders = this.getOrderByIds(orderids);
		this.addGroupforOrder(orders);
		return orders;
	}

	public int updateProcess(String orderIds, Integer state) {
		return orderMapper.updateProcess(orderIds, state);
	}

	public Order getOrderByOrderId(Long orderId) {
		Order order = orderMapper.getOrderByOrderId(orderId);
		List<Order> list = new ArrayList<Order>();
		list.add(order);
		this.addGroupforOrder(list);
		return order;
	}

	public List<Order> getOrderByIds(List<Long> ids) {
		List<Order> orders = orderMapper.getOrderByIds(StringUtils.join(ids,
				","));
		return orders;
	}

	@Transactional(rollbackFor = Throwable.class, propagation = Propagation.REQUIRED)
	public boolean canelOrder(Order order) throws Exception {
		int res = orderMapper.updateInvalid(order.getPlfOrderId(),
				order.getType());
		boolean f = false;
		if (res > 0) {
			// 达达发单也处理掉
			DeliverRecordOrder deliver = deliverMapper
					.getDeliverRecordByOrderId(order.getId());
			if (deliver != null) {
				deliverService.cancel(deliver.getId(), 4);// 顾客取消订单
			}
			if (AuserShop.SHOP_ELEME.equals(order.getType())) {
				f = elemeService.cancelOrder(order.getShopId(),
						order.getPlfOrderId());
			} else {
				f = mtService.cancelOrder(order.getShopId(),
						order.getPlfOrderId());
			}
			if (!f) {
				throw new Exception("canelOrder error");
			}
		}
		return f;
	}

	@Transactional(rollbackFor = Throwable.class, propagation = Propagation.REQUIRED)
	public boolean agreeOrder(Order order) throws Exception {
		int res = orderMapper.updateInvalid(order.getPlfOrderId(),
				order.getType());
		boolean f = false;
		if (res > 0) {
			// 达达发单也处理掉
			DeliverRecordOrder deliver = deliverMapper
					.getDeliverRecordByOrderId(order.getId());
			if (deliver != null) {
				deliverService.cancel(deliver.getId(), 4);// 顾客取消订单
			}
			if (AuserShop.SHOP_ELEME.equals(order.getType())) {
				f = elemeService.agreeRefund(order.getShopId(),
						order.getPlfOrderId());
			} else {
				f = mtService.agreeRefund(order.getShopId(),
						order.getPlfOrderId());
			}
			if (!f) {
				throw new Exception("agreeRefund error");
			}
		}
		return f;
	}
}
